<?php

namespace app\admin\model;
use think\Model;
use think\Db;

class HouseModel extends Model{

    protected $table = "a_house";

    /**
     * 根据条件获取列表信息
     * @param $where
     * @param $Nowpage
     * @param $limits
     */
    public function getAll($map, $Nowpage, $limits)
    {
        $data = $this->where($map)->page($Nowpage,$limits)->select();
        if( !empty($data) ){
            foreach($data as $k => $v){
                $answer = json_decode($v['result'],true);
                $arr = array('A'=>$answer['A'],'B'=>$answer['B'],'C'=>$answer['C'],'D'=>$answer['D']);
                unset($data[$k]['result']);
                $data[$k]['A'] = $answer['A'];
                $data[$k]['B'] = $answer['B'];
                $data[$k]['C'] = $answer['C'];
                $data[$k]['D'] = $answer['D'];
                $data[$k]['answer'] = $answer[$v['answer']];
            }
        }
        return $data;
    }

    /**
     * 插入题库
     * @param $data
     */
    public function insertHouse($data){
        $arr  = array('A'=>$data['A'],'B'=>$data['B'],'C'=>$data['C'],'D'=>$data['D']);
        $param = array('title'=>$data['title'],'answer'=>$data['answer'],'result'=>json_encode($arr));
        try{
            $result = $this->save($param);
            if(false === $result){
                return ['code' => -1, 'data' => '', 'msg' => $this->getError()];
            }else{
                return ['code' => 1, 'data' => '', 'msg' => '添加题目成功'];
            }
        }catch( PDOException $e){
            return ['code' => -2, 'data' => '', 'msg' => $e->getMessage()];
        }
    }


    public function updateHouse($data){
        $arr  = array('A'=>$data['A'],'B'=>$data['B'],'C'=>$data['C'],'D'=>$data['D']);
        $param = array('id'=>$data['id'],'title'=>$data['title'],'answer'=>$data['answer'],'result'=>json_encode($arr));
        try{
            $result = $this->update($param);
            if(false === $result){
                return ['code' => -1, 'data' => '', 'msg' => $this->getError()];
            }else{
                return ['code' => 1, 'data' => '', 'msg' => '编辑题目成功'];
            }
        }catch( PDOException $e){
            return ['code' => -2, 'data' => '', 'msg' => $e->getMessage()];
        }
    }
}
